package com.huawei.esdk.tp.northcommu.cxf.professional.convert;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import com.huawei.esdk.platform.common.SDKResult;
import com.huawei.esdk.platform.common.exception.SDKException;
import com.huawei.esdk.platform.common.utils.StringUtils;
import com.huawei.esdk.tp.common.CipherUtils;
import com.huawei.esdk.tp.common.ErrInfo;
import com.huawei.esdk.tp.common.constants.TPConstant;
import com.huawei.esdk.tp.cxf.enumgen.SiteTypeMapping;
import com.huawei.esdk.tp.domain.model.Site;
import com.huawei.esdk.tp.domain.model.bean.PagedList;
import com.huawei.esdk.tp.domain.model.bean.QueryCondition;
import com.huawei.esdk.tp.domain.model.bean.QuerySites;
import com.huawei.esdk.tp.domain.model.bean.SortField;
import com.huawei.esdk.tp.domain.model.bean.VideoCapbilityItem;
import com.huawei.esdk.tp.domain.model.bean.VideoSourcesInfo;
import com.huawei.esdk.tp.northcommu.cxf.professional.gen.AddSiteInfoEx;
import com.huawei.esdk.tp.northcommu.cxf.professional.gen.AuxStreamInfoEx;
import com.huawei.esdk.tp.northcommu.cxf.professional.gen.DoubleFilterEx;
import com.huawei.esdk.tp.northcommu.cxf.professional.gen.EditSiteInfoEx;
import com.huawei.esdk.tp.northcommu.cxf.professional.gen.FilterBaseEx;
import com.huawei.esdk.tp.northcommu.cxf.professional.gen.IntFilterEx;
import com.huawei.esdk.tp.northcommu.cxf.professional.gen.PageParamEx;
import com.huawei.esdk.tp.northcommu.cxf.professional.gen.PagesInfoEx;
import com.huawei.esdk.tp.northcommu.cxf.professional.gen.QueryAuxStreamSourcesExResponse;
import com.huawei.esdk.tp.northcommu.cxf.professional.gen.QueryConfigEx;
import com.huawei.esdk.tp.northcommu.cxf.professional.gen.QueryMainStreamSourcesExResponse;
import com.huawei.esdk.tp.northcommu.cxf.professional.gen.QuerySiteVersionInfoExResponse;
import com.huawei.esdk.tp.northcommu.cxf.professional.gen.QuerySitesInfoEx;
import com.huawei.esdk.tp.northcommu.cxf.professional.gen.QuerySitesInfoExResponse;
import com.huawei.esdk.tp.northcommu.cxf.professional.gen.QueryVideoOutSrcStateExResponse;
import com.huawei.esdk.tp.northcommu.cxf.professional.gen.SiteDeviceVersionInfoEx;
import com.huawei.esdk.tp.northcommu.cxf.professional.gen.SiteMicVersionMapEx;
import com.huawei.esdk.tp.northcommu.cxf.professional.gen.SortItemEx;
import com.huawei.esdk.tp.northcommu.cxf.professional.gen.StringFilterEx;
import com.huawei.esdk.tp.northcommu.cxf.professional.gen.TerminalInfoEx;
import com.huawei.esdk.tp.northcommu.cxf.professional.gen.VideoCapbilityItemEx;
import com.huawei.esdk.tp.northcommu.cxf.professional.gen.VideoSourcesInfoEx;

public class TPProfessionalSiteMgrConvert
{
    public QueryVideoOutSrcStateExResponse queryVideoOutSrcStateExConvert(List<VideoSourcesInfo> vsiList)
    {
        QueryVideoOutSrcStateExResponse response = new QueryVideoOutSrcStateExResponse();
        List<VideoSourcesInfoEx> vsiExList = response.getVideoSourcesInfos();
        
        for (VideoSourcesInfo vsi : vsiList)
        {
            VideoSourcesInfoEx vsiEx = new VideoSourcesInfoEx();
            vsiEx.setSourcesId(vsi.getSourcesID());
            vsiEx.setSourcesName(vsi.getSourcesName());
            vsiEx.setSourcesState(vsi.getSourcesState());
            vsiExList.add(vsiEx);
        }
        response.setResultCode(0);
        return response;
    }
    
    public QueryMainStreamSourcesExResponse queryMainStreamSourcesExConvert(Map<Integer, String> requestMap)
    {
        QueryMainStreamSourcesExResponse response = new QueryMainStreamSourcesExResponse();
        if (null == requestMap || requestMap.isEmpty())
        {
            return response;
        }
        
        AuxStreamInfoEx auxStreamInfoEx = null;
        Set<Map.Entry<Integer, String>> entries = requestMap.entrySet();
        for (Map.Entry<Integer, String> entry : entries)
        {
            auxStreamInfoEx = new AuxStreamInfoEx();
            auxStreamInfoEx.setId(entry.getKey());
            auxStreamInfoEx.setName(entry.getValue());
            response.getAuxStreams().add(auxStreamInfoEx);
        }
        response.setResultCode(0);
        return response;
    }
    
    public QueryAuxStreamSourcesExResponse sdkResult2QueryAuxStreamSourcesExResponse(
        SDKResult<Map<Integer, String>> result)
    {
        QueryAuxStreamSourcesExResponse response = new QueryAuxStreamSourcesExResponse();
        response.setResultCode((int)result.getErrCode());
        if (null != result.getResult() && result.getResult().size() > 0)
        {
            AuxStreamInfoEx auxStreamInfoEx = null;
            for (Integer key : result.getResult().keySet())
            {
                auxStreamInfoEx = new AuxStreamInfoEx();
                auxStreamInfoEx.setId(key);
                auxStreamInfoEx.setName(result.getResult().get(key));
                response.getAuxStreams().add(auxStreamInfoEx);
            }
        }
        
        return response;
    }
    
    public QuerySiteVersionInfoExResponse sdkResult2QuerySiteVersionInfoExResponse(SDKResult<Site> result)
    {
        QuerySiteVersionInfoExResponse response = new QuerySiteVersionInfoExResponse();
        response.setResultCode(Integer.parseInt(String.valueOf(result.getErrCode())));
        if (null != result.getResult())
        {
            Site site = result.getResult();
            SiteDeviceVersionInfoEx siteDeviceVersionInfoEx = new SiteDeviceVersionInfoEx();
            siteDeviceVersionInfoEx.setHardVersion(site.getHardVersion());
            siteDeviceVersionInfoEx.setLicense(site.getLisence());
            siteDeviceVersionInfoEx.setLogicVersion(site.getLogicVersion());
            siteDeviceVersionInfoEx.setManufacturer(TPConstant.MANU_FACTURER);
            siteDeviceVersionInfoEx.setModel(site.getModel());
            siteDeviceVersionInfoEx.setSoftVersion(site.getSoftVersion());
            
            Map<String, String> micVersionMap = site.getMicVersion();
            if (null != micVersionMap)
            {
                SiteMicVersionMapEx version = null;
                Set<Map.Entry<String, String>> entries = micVersionMap.entrySet();
                for (Map.Entry<String, String> entry : entries)
                {
                    version = new SiteMicVersionMapEx();
                    version.setMicIP(entry.getKey());
                    version.setVersion(entry.getValue());
                    siteDeviceVersionInfoEx.getMicVersions().add(version);
                }
            }
            response.setSiteDeviceVersionInfo(siteDeviceVersionInfoEx);
        }
        return response;
    }
    
    public QuerySites queryAllSitesExSoap2Modal(QuerySitesInfoEx parameters)
        throws SDKException
    {
        QuerySites querySites = new QuerySites();
        QueryConfigEx queryConfig = parameters.getQueryConfig();
        
        PageParamEx pageInfo = queryConfig.getPageParam();
        if (null != pageInfo)
        {
            querySites.setCurrentPage(pageInfo.getCurrentPage());
            querySites.setNumberPerPage(pageInfo.getNumberPerPage());
        }
        
        List<SortItemEx> sortItems = queryConfig.getSortItems();
        if (!sortItems.isEmpty())
        {
            List<SortField> sortItemsModal = new ArrayList<SortField>();
            for (SortItemEx stItem : sortItems)
            {
                Integer itemIndex = stItem.getItemIndex();
                Integer sort = stItem.getSort();
                
                // DTS2015012706783 
                // 非必填参数不为空时，北向转换校验其必填属性
                if (null == itemIndex || null == sort)
                {
                    SDKException sdkException = new SDKException(ErrInfo.SDK_PARAM_NOT_COMPLETE_ERRORDESC);
                    sdkException.setSdkErrCode(ErrInfo.SDK_PARAM_NOT_COMPLETE_ERRORCODE);
                    throw sdkException;
                }
                
                SortField sortField = new SortField();
                sortField.setIsAscend(sort);
                sortField.setFieldIndex(itemIndex);
                sortItemsModal.add(sortField);
            }
            querySites.setSortField(sortItemsModal);
        }
        
        List<FilterBaseEx> filters = queryConfig.getFilters();
        if (!filters.isEmpty())
        {
            List<QueryCondition> queryConditions = new ArrayList<QueryCondition>();
            for (FilterBaseEx ftItem : filters)
            {
                Integer columnIndex = ftItem.getColumnIndex();
                
                // DTS2015012706783 
                // 非必填参数不为空时，北向转换校验其必填属性
                if (null == columnIndex)
                {
                    SDKException sdkException = new SDKException(ErrInfo.SDK_PARAM_NOT_COMPLETE_ERRORDESC);
                    sdkException.setSdkErrCode(ErrInfo.SDK_PARAM_NOT_COMPLETE_ERRORCODE);
                    throw sdkException;
                }
                QueryCondition queryCondition = getQueryConditionSoap2Modal(ftItem);
                if (null != queryCondition)
                {
                    queryConditions.add(queryCondition);
                }
            }
            querySites.setQueryCondition(queryConditions);
        }
        
        if (null != queryConfig.getFocusItem())
        {
            querySites.setFocusItem((long)queryConfig.getFocusItem());
        }
        
        return querySites;
    }
    
    public QuerySitesInfoExResponse queryAllSitesExModal2Soap(SDKResult<PagedList<Site>> sites)
        throws SDKException
    {
        QuerySitesInfoExResponse response = new QuerySitesInfoExResponse();
        List<TerminalInfoEx> siteInfoExs = new ArrayList<TerminalInfoEx>();
        response.setResultCode((int)sites.getErrCode());
        if (0 != sites.getErrCode())
        {
            return response;
        }
        
        if (null != sites.getResult().getRecords() && sites.getResult().getRecords().size() > 0)
        {
            List<Site> records = sites.getResult().getRecords();
            TerminalInfoEx siteInfo = null;
            for (int i = 0; i < records.size(); i++)
            {
                siteInfo = new TerminalInfoEx();
                siteInfo.setName(records.get(i).getName());
                siteInfo.setUri(records.get(i).getUri());
                siteInfo.setType(SiteTypeMapping.string2Int(records.get(i).getSiteType()));
                //C30新增
                siteInfo.setRate(records.get(i).getRate());
                //C50新增
                siteInfo.setRegUser(records.get(i).getRegUser());
                siteInfo.setRegPassword(CipherUtils.encodeFromBase64(records.get(i).getRegPassword()));
                if (null != records.get(i).getVideoCapbilitys())
                {
                    for (VideoCapbilityItem vedioCap : records.get(i).getVideoCapbilitys())
                    {
                        VideoCapbilityItemEx vedioCapSoap = new VideoCapbilityItemEx();
                        vedioCapSoap.setVideoProtocol(vedioCap.getVideoProtocol());
                        vedioCapSoap.getVideoFormat().addAll(vedioCap.getVideoFormats());
                        siteInfo.getVideoCapbility().add(vedioCapSoap);
                    }
                }
                
                siteInfoExs.add(siteInfo);
            }
        }
        response.getSites().addAll(siteInfoExs);
        
        PagesInfoEx pageInfo = new PagesInfoEx();
        pageInfo.setCurrentPage(sites.getResult().getCurPageNo());
        pageInfo.setTotalPages(sites.getResult().getTotalPageCount());
        pageInfo.setTotalRecords(sites.getResult().getTotalRecordCount());
        response.setPageInfo(pageInfo);
        
        return response;
    }
    
    private QueryCondition getQueryConditionSoap2Modal(FilterBaseEx filtersEx)
    {
        if (StringFilterEx.class.isInstance(filtersEx))
        {
            StringFilterEx filtersEx1 = (StringFilterEx)filtersEx;
            QueryCondition queryCondition = new QueryCondition();
            queryCondition.setConditionName("StringFilterEx");
            queryCondition.setConditionType("1");
            queryCondition.setConditionValue(new Object[] {filtersEx1.getColumnIndex(), filtersEx1.getValue()});
            return queryCondition;
        }
        else if (IntFilterEx.class.isInstance(filtersEx))
        {
            IntFilterEx filtersEx1 = (IntFilterEx)filtersEx;
            QueryCondition queryCondition = new QueryCondition();
            queryCondition.setConditionName("IntFilterEx");
            queryCondition.setConditionType("2");
            queryCondition.setConditionValue(new Object[] {filtersEx1.getColumnIndex(), filtersEx1.getGreaterThan(),
                filtersEx1.getLessThan(), filtersEx1.getEqualTo()});
            return queryCondition;
        }
        else if (DoubleFilterEx.class.isInstance(filtersEx))
        {
            DoubleFilterEx filtersEx1 = (DoubleFilterEx)filtersEx;
            QueryCondition queryCondition = new QueryCondition();
            queryCondition.setConditionName("DoubleFilterEx");
            queryCondition.setConditionType("3");
            queryCondition.setConditionValue(new Object[] {filtersEx1.getColumnIndex(), filtersEx1.getGreaterThan(),
                filtersEx1.getLessThan(), filtersEx1.getEqualTo()});
            return queryCondition;
        }
        else
        {
            return null;
        }
        
    }
    
    public Site addSiteInfoExSoap2Modal(AddSiteInfoEx parameters)
        throws SDKException
    {
        Site sitesInfo = new Site();
        sitesInfo.setOrgId(parameters.getOrgId());
        
        TerminalInfoEx terminalInfo = parameters.getSiteInfo();
        
        if (null != terminalInfo)
        {
            getSiteInfoEx(sitesInfo, terminalInfo);
        }
        
        return sitesInfo;
    }
    
    public Site editSiteInfoExSoap2Modal(EditSiteInfoEx parameters)
        throws SDKException
    {
        Site sitesInfo = new Site();
        
        TerminalInfoEx terminalInfo = parameters.getSiteInfo();
        
        if (null != terminalInfo)
        {
            getSiteInfoEx(sitesInfo, terminalInfo);
        }
        
        return sitesInfo;
    }

    private void getSiteInfoEx(Site sitesInfo, TerminalInfoEx terminalInfo)
        throws SDKException
    {
        sitesInfo.setName(terminalInfo.getName());
        sitesInfo.setRate(terminalInfo.getRate());
        
        if (!StringUtils.isEmpty(terminalInfo.getRegPassword()))
        {
            String encryptedPwd = CipherUtils.decodeFromBase64(terminalInfo.getRegPassword());
            if (null != encryptedPwd && !encryptedPwd.isEmpty())
            {
                sitesInfo.setRegPassword(encryptedPwd);
            }
            else
            {
                SDKException sdkException = new SDKException(ErrInfo.SDK_TP_PASSWORD_DECODE_ERRORDESC);
                sdkException.setSdkErrCode(ErrInfo.SDK_TP_PASSWORD_DECODE_ERRORCODE);
                throw sdkException;
            }
        }
        else
        {
            sitesInfo.setRegPassword(terminalInfo.getRegPassword());
        }
        
        sitesInfo.setRegUser(terminalInfo.getRegUser());
        sitesInfo.setType(terminalInfo.getType());
        sitesInfo.setUri(terminalInfo.getUri());
        
        // modify by c00316442 2015.2.3, findbugs NP_NULL_ON_SOME_PATH
        List<VideoCapbilityItemEx> videoCapbility = terminalInfo.getVideoCapbility();
        
        if (!videoCapbility.isEmpty())
        {
            VideoCapbilityItem vdieoCapbilityItem = null;
            
            for (VideoCapbilityItemEx videoCapbilityItemEx : videoCapbility)
            {
                vdieoCapbilityItem = new VideoCapbilityItem();
                
                Integer videoProtocol = videoCapbilityItemEx.getVideoProtocol();
                
                if (null == videoProtocol)
                {
                    // DTS2015012702216
                    // 非必填参数不为空时，校验其必填属性
                    SDKException sdkException = new SDKException(ErrInfo.SDK_PARAM_NOT_COMPLETE_ERRORDESC);
                    sdkException.setSdkErrCode(ErrInfo.SDK_PARAM_NOT_COMPLETE_ERRORCODE);
                    throw sdkException;
                }
                
                vdieoCapbilityItem.setVideoProtocol(videoProtocol);
                
                List<Integer> videoFormats = videoCapbilityItemEx.getVideoFormat();
                
                if (!videoFormats.isEmpty())
                {
                    for (Integer videoFormat : videoFormats)
                    {
                        if (null == videoFormat)
                        {
                            // 非必填参数不为空时，校验其必填属性
                            SDKException sdkException = new SDKException(ErrInfo.SDK_PARAM_NOT_COMPLETE_ERRORDESC);
                            sdkException.setSdkErrCode(ErrInfo.SDK_PARAM_NOT_COMPLETE_ERRORCODE);
                            throw sdkException;
                        }
                        
                        vdieoCapbilityItem.getVideoFormats().add(videoFormat);
                    }
                }
                
                sitesInfo.getVideoCapbilitys().add(vdieoCapbilityItem);
            }
        }
    }
    
}
